package com.xxxx.server.controller;

import com.xxxx.server.mapper.AddUserMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Userauthority;
import com.xxxx.server.service.IAddUserService;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.service.IUserauthorityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(value = "注册用户",tags = "注册用户")
@RestController
@RequestMapping("/")
public class AddUserController {

    @Autowired
    private AddUserMapper addUserMapper;

    @Autowired
    private IAddUserService addUserService;

    @Autowired IUserauthorityService userauthorityService;


    @ApiOperation(value = "注册用户")
    @PostMapping("/register")

    public RespBean addAdmin(@RequestBody Admin admin)
    {
        String addUserName=admin.getUsername();
     List<Admin> result=addUserService.getDataByAddUserName(addUserName);
        System.out.println("重复数据查询结果为:"+result);
     if(result.size()==0)
     {
         BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         // 加密
         String encodedPassword = passwordEncoder.encode(admin.getPassword().trim());

         admin.setPassword(encodedPassword);

         boolean result1=addUserService.save(admin);
         if(result1)
         {
                     Userauthority userauthority=new Userauthority();
        userauthority.setId(0);
        userauthority.setUserId(admin.getId());
        userauthority.setAuthorityId(2);
        //添加讲座查询权限
        userauthorityService.save(userauthority);



             return RespBean.success("注册成功,请登录");
         }
         else
         {
             return RespBean.error("注册失败!");
         }

     }
     else
     {
         return RespBean.error("注册失败，用户名已重复");
     }

    }
}
